from flask import Flask, Blueprint, request, redirect, session, render_template, current_app
from app.config import create_db_connection

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    return render_template('index.html')

# 验证用户名和密码
def validate_user(username, password):
    conn, cursor = create_db_connection()

    query = "SELECT * FROM users WHERE username = %s AND password = %s"
    cursor.execute(query, (username, password))
    result = cursor.fetchone()

    cursor.close()
    conn.close()

    return bool(result)

# 设置登录检查装饰器
def login_required(func):
    def wrapper(*args, **kwargs):
        # 检查用户是否已登录
        if 'username' not in session:
            return redirect('/login')  # 重定向到登录页面

        return func(*args, **kwargs)

    return wrapper

@main_bp.before_request
def check_login():
    # 排除登录和静态资源请求
    if request.path == '/login' or request.path.startswith('/static'):
        return

    # 检查用户是否已登录
    if 'username' not in session:
        return redirect('/login')  # 重定向到登录页面

# 受保护的路由，需要登录才能访问
@main_bp.route('/protected')
@login_required
def protected_route():
    return '这是一个受保护的路由'

@main_bp.route('/logout', methods=['POST'])
def logout():
    session.pop('username', None)  # 从会话中删除用户名
    return redirect('/login')  # 重定向到登录页面

# 定义登录路由
@main_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if username and password:
            if validate_user(username, password):
                session['username'] = username  # 将用户名存储在会话中
                return redirect('/index')  # 登录成功后重定向到index页面
            else:
                error_message = '用户名或密码错误'
                return render_template('login.html', error_message=error_message)
        else:
            error_message = '请输入用户名和密码'
            return render_template('login.html', error_message=error_message)

    # 处理GET请求
    return render_template('login.html')

@main_bp.route('/index', endpoint='index_page')
@login_required
def index_page():
    return render_template('index.html')
